package dao.Impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import dao.BaseDao;
import dao.FinancingProductDao;
import entity.FinancingProduct;

public class FinancingProductDaoImpl extends BaseDao implements FinancingProductDao{

	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	@Override
	public List<FinancingProduct> list(String id,int risk) {
		List<FinancingProduct> list=new ArrayList<FinancingProduct>();
		try {
			conn=super.getConnection();
			String sql="";
			if (id=="" || id==null && risk==0) {
				sql+="select * from FinancingProduct ";
			}else{
				sql+="select * from FinancingProduct where id like '%"+id+"%' and risk="+risk;
				
			}
			sql+=" ORDER BY saleStarting DESC";
			
			pstmt=conn.prepareStatement(sql);
			
			rs=pstmt.executeQuery();
			while (rs.next()) {
				FinancingProduct pro=new FinancingProduct();
				pro.setId(rs.getString("id"));
				pro.setRisk(rs.getInt("risk"));
				pro.setIncome(rs.getString("income"));
				pro.setSaleStarting(rs.getString("saleStarting"));
				pro.setSaleEnd(rs.getString("saleEnd"));
				pro.setEnd(rs.getString("end"));
				list.add(pro);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			super.closeAll(conn, pstmt, rs);
		}
		return list;
	}

	@Override
	public int BindId(String id) {
		int result=0;
		try {
			conn=super.getConnection();
			String sql="select count(1) from FinancingProduct where id=?";
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, id);
			rs=pstmt.executeQuery();
			while (rs.next()) {
				result=rs.getInt(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			super.closeAll(conn, pstmt, rs);
		}
		return result;
	}

	@Override
	public int add(FinancingProduct product) {
		int result=0;
		try {
			conn=super.getConnection();
			String sql="insert into FinancingProduct(id,risk,income,saleStarting,saleEnd,end) values(?,?,?,?,?,?)";
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, product.getId());
			pstmt.setInt(2, product.getRisk());
			pstmt.setString(3, product.getIncome());
			pstmt.setString(4, product.getSaleStarting());
			pstmt.setString(5, product.getSaleEnd());
			pstmt.setString(6, product.getEnd());
			result=pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			super.closeAll(conn, pstmt, rs);
		}
		return result;
	}

}
